import { useUserStore } from '@/stores/modules/user.js'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router/index.js'

const baseURL = import.meta.env.VITE_API_BASE

const instance = axios.create({
  baseURL,
  timeout: 100000
})

instance.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = userStore.token
    }
    return config
  },
  err => Promise.reject(err)
)

instance.interceptors.response.use(
  res => {
    if (res.data.code === 0 || res.data.code === 40302 || res.data.code === 40303) {
      return res.data
    }

    if (res.data.code === 40100) {
      ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const userStore = useUserStore()
          userStore.clear()
          router.push('/login')
        })
        .catch(() => {})
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    }

    ElMessage.error({ message: res.data.msg || '服务异常' })
    return Promise.reject(res.data)
  },
  err => {
    console.log('err' + err)
    let { message } = err
    if (message === 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status emailCode')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    ElMessage.error(message)
    return Promise.reject(err)
  }
)

export default instance
export { baseURL }
